//
//  PlanOtherCell.m
//  SportSocial
//
//  Created by yull on 15/2/3.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "PlanOtherCell.h"

@interface PlanOtherCell ()

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation PlanOtherCell
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        CGRect rect = CGRectMake(15, 0, self.contentView.width - 30, self.contentView.height);
        UIView *backView = [[UIView alloc] initWithFrame:rect];
        backView.backgroundColor = RGB(255, 247, 239);
        backView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.contentView addSubview:backView];
        
        rect = CGRectMake(0, backView.height - 1, backView.width, 1);
        UIView *lineView = [[UIView alloc] initWithFrame:rect];
        lineView.backgroundColor = RGB(248, 238, 225);
        lineView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        [backView addSubview:lineView];
        
        rect = CGRectMake(10, 15, 40, 40);
        self.iconImageView = [[UIImageView alloc] initWithFrame:rect];
        self.iconImageView.layer.cornerRadius = 20.0f;
        self.iconImageView.layer.masksToBounds = YES;
        [backView addSubview:self.iconImageView];
        
        rect = CGRectMake(self.iconImageView.left, self.iconImageView.bottom+15, self.iconImageView.width, 25);
        self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.deleteButton.frame = rect;
        self.deleteButton.backgroundColor = RGB(195, 81, 8);
        [self.deleteButton setTitle:@"删除" forState:UIControlStateNormal];
        [self.deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.deleteButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [backView addSubview:self.deleteButton];
        
        rect.origin.x = backView.width - rect.origin.x - rect.size.width;
        self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.shareButton.frame = rect;
        self.shareButton.backgroundColor = RGB(104, 202, 27);
        [self.shareButton setTitle:@"分享" forState:UIControlStateNormal];
        [self.shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.shareButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        self.shareButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [backView addSubview:self.shareButton];
        
        self.photoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.photoButton.frame = rect;
        self.photoButton.backgroundColor = RGB(104, 202, 27);
        self.photoButton.right = self.shareButton.left - 10;
        [self.photoButton setTitle:@"拍照" forState:UIControlStateNormal];
        [self.photoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.photoButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        self.photoButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [backView addSubview:self.photoButton];
        
        rect.origin.x = self.iconImageView.right + 10;
        rect.origin.y = self.iconImageView.top + 5;
        self.endButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.endButton.frame = rect;
        self.endButton.backgroundColor = RGB(104, 202, 27);
        [self.endButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.endButton.titleLabel.font = [UIFont systemFontOfSize:12.0f];
        [backView addSubview:self.endButton];
        
        rect.origin.x = self.endButton.right + 10;
        rect.size.width = backView.width - rect.origin.x - 10;
        self.timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.timeButton.frame = rect;
        self.timeButton.backgroundColor = [UIColor whiteColor];
        [self.timeButton setTitleColor:RGB(201, 67, 72) forState:UIControlStateNormal];
        self.timeButton.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [backView addSubview:self.timeButton];
        
        rect.origin.y = self.timeButton.bottom + 5;
        rect.size.height = 15.0f;
        self.calorieLabel = [[UILabel alloc] initWithFrame:rect];
        self.calorieLabel.backgroundColor = [UIColor clearColor];
        self.calorieLabel.textColor = RGB(201, 67, 72);
        self.calorieLabel.font = [UIFont systemFontOfSize:15.0f];
        self.calorieLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        [backView addSubview:self.calorieLabel];
        
        [self.endButton addTarget:self action:@selector(onClickEndButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.timeButton addTarget:self action:@selector(onClickTimeButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.deleteButton addTarget:self action:@selector(onClickDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.shareButton addTarget:self action:@selector(onClickShareButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.photoButton addTarget:self action:@selector(onClickPhotoButton:) forControlEvents:UIControlEventTouchUpInside];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateSportTime) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    return self;
}

- (void)drawCellWithPlanInfo:(PlanInfo *)planInfo
{
    self.planInfo = planInfo;
    
//    @autoreleasepool {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        dateFormatter.dateFormat = @"yyyy-MM-dd";
//        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
//        NSDate *selectDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%2d-%2d", planInfo.year, planInfo.month, planInfo.day]];
//        selectDate = [NSDate dateWithTimeInterval:[timeZone secondsFromGMT] sinceDate:selectDate];
//        
//        NSTimeInterval nowTimeInterval = floor([[NSDate date] timeIntervalSince1970]);
//        NSDate *tomorrowDate = [NSDate dateWithTimeIntervalSince1970:nowTimeInterval - ((unsigned long long)nowTimeInterval % 86400) + 86399];
//        
//        if ([selectDate compare:tomorrowDate] == NSOrderedDescending) {
//            self.endButton.hidden = YES;
//            self.photoButton.hidden = YES;
//            self.shareButton.hidden = YES;
//        }
//    }
    
    self.iconImageView.image = [UIImage imageNamed:planInfo.icon];
    
    self.calorieLabel.text = [[NSString alloc] initWithFormat:@"卡路里消耗%d大卡",planInfo.calorie];
    
    [self updateSportTime];
    [self updateCellWithStatus];
}

- (void)updateCellWithStatus
{
    if (self.planInfo.status == PlanInfoStatusNone) {
        self.endButton.enabled = YES;
        [self.endButton setTitle:@"开始" forState:UIControlStateNormal];
//        self.deleteButton.hidden = NO;
    }else if (self.planInfo.status == PlanInfoStatusStart) {
        self.endButton.enabled = YES;
        [self.endButton setTitle:@"结束" forState:UIControlStateNormal];
//        self.deleteButton.hidden = NO;
    }else if (self.planInfo.status == PlanInfoStatusStop){
        self.endButton.enabled = YES;
        [self.endButton setTitle:@"完成" forState:UIControlStateNormal];
//        self.deleteButton.hidden = NO;
    }else {
        self.endButton.enabled = NO;
        [self.endButton setTitle:@"已完成" forState:UIControlStateNormal];
//        self.deleteButton.hidden = YES;
    }
}

- (void)updateSportTime
{
    NSString *timeStr = nil;
    
    NSTimeInterval time = 0;
    if (self.planInfo.end_date && self.planInfo.start_date) {
        
        time = self.planInfo.end_date - self.planInfo.start_date;
        
    } else if (self.planInfo.start_date) {
        
        time = [[NSDate date] timeIntervalSince1970] - self.planInfo.start_date;
        
    }
    
    if (time > 86399) {
        time = 86399;
    }
    
    if (time > 3600) {
        timeStr = [NSString stringWithFormat:@"%02d:%02d:%02d", (NSInteger)time/3600, ((NSInteger)time%3600)/60, (NSInteger)time%60];
    } else {
        timeStr = [NSString stringWithFormat:@"%02d:%02d", ((NSInteger)time%3600)/60, (NSInteger)time%60];
    }
    
    if (timeStr.length == 0) {
        timeStr = @"00:00";
    }
    
    UIColor *textColor = RGB(201, 67, 72);
    
    NSDictionary *dict1 = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0f],
                            NSForegroundColorAttributeName:textColor};
    NSAttributedString *attr1 = [[NSAttributedString alloc] initWithString:@"计时 " attributes:dict1];
    
    NSDictionary *dict2 = @{NSFontAttributeName : [UIFont systemFontOfSize:20.0f],
                            NSForegroundColorAttributeName:textColor};
    NSAttributedString *attr2 = [[NSAttributedString alloc] initWithString:timeStr attributes:dict2];
    
    NSMutableAttributedString *returnAttr = [[NSMutableAttributedString alloc] initWithAttributedString:attr1];
    [returnAttr appendAttributedString:attr2];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.timeButton setAttributedTitle:returnAttr forState:UIControlStateNormal];
    });
}

- (NSInteger)calculateCalorie
{
    NSTimeInterval time = self.planInfo.end_date - self.planInfo.start_date;

    if ([self.planInfo.sport_name isEqualToString:@"篮球"]) {
        return (time / 1800) * 220;
    } else if ([self.planInfo.sport_name isEqualToString:@"足球"]) {
        return (time / 1800) * 270;
    } else if ([self.planInfo.sport_name isEqualToString:@"台球"]) {
        return (time / 3600) * 300;
    } else if ([self.planInfo.sport_name isEqualToString:@"网球"]) {
        return (time / 3600) * 425;
    } else if ([self.planInfo.sport_name isEqualToString:@"乒乓球"]) {
        return (time / 3600) * 360;
    } else if ([self.planInfo.sport_name isEqualToString:@"游泳"]) {
        return (time / 3600) * 590;
    }
    
    return 0;
}

#pragma mark - Action
- (void)onClickEndButton:(id)sender
{
    PlanInfoStatus status = self.planInfo.status;
    if (status == PlanInfoStatusNone) {
        self.planInfo.status = PlanInfoStatusStart;
        self.planInfo.start_date = [[NSDate date] timeIntervalSince1970];
        
        [self updateCellWithStatus];
        
        if ([self.delegate respondsToSelector:@selector(updatePlanInfo:)]) {
            [self.delegate updatePlanInfo:self.planInfo];
        }
    }else if (status == PlanInfoStatusStart) {
        self.planInfo.status = PlanInfoStatusStop;
        self.planInfo.end_date = [[NSDate date] timeIntervalSince1970];
        self.planInfo.calorie = [self calculateCalorie];
        
        self.calorieLabel.text = [[NSString alloc] initWithFormat:@"卡路里消耗%d大卡",self.planInfo.calorie];
        [self updateCellWithStatus];
        
        if ([self.delegate respondsToSelector:@selector(updatePlanInfo:)]) {
            [self.delegate updatePlanInfo:self.planInfo];
        }
    }else if (status == PlanInfoStatusStop) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定完成吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 11;
        [alert show];
    }
}

- (void)onClickTimeButton:(id)sender
{
    if (self.planInfo.status == PlanInfoStatusStop) {
        if ([self.delegate respondsToSelector:@selector(selectTimeInCell:)]) {
            [self.delegate selectTimeInCell:self];
        }
    }
}

- (void)onClickDeleteButton:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 10;
    [alert show];
}

- (void)onClickShareButton:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(shareWithPlanInfo:)]) {
        [self.delegate shareWithPlanInfo:self.planInfo];
    }
}

- (void)onClickPhotoButton:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(takePhotoWithPlanInfo:)]) {
        [self.delegate takePhotoWithPlanInfo:self.planInfo];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 10) {
        if (buttonIndex == 1) {
            if ([self.delegate respondsToSelector:@selector(deleteInfo:)]) {
                [self.delegate deleteInfo:self.planInfo];
            }
        }
    }else {
        if (buttonIndex == 1) {
            self.planInfo.status = PlanInfoStatusEnd;
            [self updateCellWithStatus];
            
            if ([self.delegate respondsToSelector:@selector(updatePlanInfo:)]) {
                [self.delegate updatePlanInfo:self.planInfo];
            }
        }
    }
}
@end
